using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;


public class GhostsHandler : MonoBehaviour {
	
	private static GhostsHandler instance;
 
	public static GhostsHandler Instance
	{
		get
		{
			if (instance == null)
			{
				instance = new GameObject("Ghosts").AddComponent<GhostsHandler> ();
			}
 
			return instance;
		}
	}
	
	private Dictionary<int,GameObject> listGhosts;
 
	public void OnApplicationQuit ()
	{
		instance = null;
	}
	
	void Awake(){
		listGhosts = new Dictionary<int, GameObject>();
	}
	
	public void createGhost(GPObject gpo){
		if(gpo.Type == ObjectType.LaserGenerator || gpo.Type == ObjectType.LaserReceiver || gpo.Type == ObjectType.Unknown || gpo.IsFixed){
			return;	
		}
		
		GameObject ghost = Instantiate(Resources.Load("Prefabs/Ghosts/"+gpo.Type+"Ghost")) as GameObject;
		ghost.transform.parent = transform;
		ghost.transform.position = gpo.Position;
		ghost.transform.eulerAngles = new Vector3(0,0,gpo.Rotation);
		
		if(gpo.Type == ObjectType.Filter){
			ghost.transform.GetChild(0).renderer.material.SetColor("_Color",gpo.ObjColor);
			ghost.GetComponent<GhostCollideHandler>().color = gpo.ObjColor;
		}
		
		listGhosts.Add(gpo.Id,ghost);
	}
	
	public void spawnAllGhosts(){
		foreach(GameObject tangible in LevelHandler.Instance.tangibles.Values){
			createGhost(new GPObject(tangible));
		}
	}
	
	public void destroyGhost(int id){
		GameObject ghost;
		if(listGhosts.TryGetValue(id,out ghost)){
			listGhosts.Remove(id);
			Destroy(ghost);
		}
		
	}
	
	public void cleanGhosts(){
		foreach(Transform child in transform){
			Destroy(child.gameObject);
		}
		
		listGhosts.Clear();
	}
	
	public bool shouldBeMoved(int id){
		if(listGhosts.ContainsKey(id)){
			return true;
		}
		return false;
	}
	
}
